package com.quanyan.assets.service.impl;

import com.alibaba.rocketmq.common.message.MessageExt;
import com.quanyan.api.APIRequest;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.AssetsPayReceive;
import com.quanyan.api.enums.AssetsType;
import com.quanyan.assets.emun.AssetsErrorEnum;
import com.quanyan.assets.emun.OpType;
import com.quanyan.assets.emun.StatusType;
import com.quanyan.assets.entity.TbUserAssets;
import com.quanyan.assets.entity.TbUserAssetsExample;
import com.quanyan.assets.entity.TbUserEggsAccumulateHistory;
import com.quanyan.assets.mapper.ETbUserAssetsMapper;
import com.quanyan.assets.mapper.ETbUserEggsAccumulateHistoryMapper;
import com.quanyan.assets.mapper.TbUserAssetsMapper;
import com.quanyan.assets.mapper.TbUserEggsAccumulateHistoryMapper;
import com.quanyan.assets.repository.EggsAccumulateHistoryRepository;
import com.quanyan.assets.repository.UserAssetsRepository;
import com.quanyan.assets.request.ReqBatchAddEgg;
import com.quanyan.assets.request.ReqUserAccumulateModify;
import com.quanyan.assets.service.MqConsumerService;
import com.quanyan.assets.service.UserAssetsService;
import com.quanyan.assets.service.UtilCurrencyService;
import com.quanyan.comment.enums.TaskEnum;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.exception.BizException;
import com.quanyan.common.utils.CommonUtils;
import com.quanyan.common.utils.GsonUtils;
import com.quanyan.common.utils.ObjectUtil;
import com.quanyan.common.utils.StringUtil;
import com.quanyan.mq.client.QcMsgClient;
import com.quanyan.mq.client.reqeust.MqRequestMsg;
import com.quanyan.orderpay.response.mq.OrderNotifyMsg;
import com.quanyan.redisCluster.utils.JsonUtil;
import com.quanyan.user.mq.UserTaskMsg;
import com.quanyan.user.response.RespUserInfoBase;
import com.quanyan.user.serviceFacade.UserServiceFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wmb on 2016/6/29.
 */
@Service("mqConsumerService")
public class MqConsumerServiceImpl implements MqConsumerService {
    @Autowired
    private EggsAccumulateHistoryRepository eggsAccumulateHistoryRepository;
    @Autowired
    private UtilCurrencyService utilCurrencyService;
    @Autowired
    private ETbUserAssetsMapper eTbUserAssetsMapper;
    @Autowired
    private UserAssetsRepository userAssetsRepository;
    @Autowired
    private TbUserEggsAccumulateHistoryMapper tbUserEggsAccumulateHistoryMapper;
    @Autowired
    private UserAssetsService userAssetsService;
    @Autowired
    private QcMsgClient qcMsgClient;
    @Autowired
    private TbUserAssetsMapper tbUserAssetsMapper;
    @Autowired
    private UserServiceFacade userServiceFacade;
    @Autowired
    private ETbUserEggsAccumulateHistoryMapper eTbUserEggsAccumulateHistoryMapper;
    private static final Logger logger = LoggerFactory.getLogger(MqConsumerService.class);
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void eggsRechange(MessageExt messageExt) {
//        byte[] bodyByte = messageExt.getBody();
//        //获取成功返回的信息
//        OrderNotifyMsg orderNotifyMsg = (OrderNotifyMsg) ObjectUtil.toObject(bodyByte);
//        System.out.println("鸟蛋充值<<<<<<<<<<<<<<<<<<<<<<<" + orderNotifyMsg.getOutTradeNo());
//        //鸟蛋充值有对应流水号
//        if (!StringUtil.isBlankOrNull(orderNotifyMsg.getOutTradeNo())) {
//            if (orderNotifyMsg.getResultCode() != null) {
//                switch (orderNotifyMsg.getResultCode()) {
//                    //支付成功处理
//                    case OrderNotifyMsg.RESULT_CODE_USER_PAY_SUCCESS:
//                        //更新历史状态
//                        int updateStatus = eggsAccumulateHistoryRepository.updateRechangeStatus(orderNotifyMsg.getOutTradeNo(), StatusType.EFFECTIVE.id.byteValue());
//                        TbUserEggsAccumulateHistory tbUserEggsAccumulateHistory = eggsAccumulateHistoryRepository.selectRechangeBySerialNumber(orderNotifyMsg.getOutTradeNo());
//                        if (updateStatus == 1) {
//                            Long accumulate = orderNotifyMsg.getPayAmount().multiply(utilCurrencyService.exchangeAssetsAmount(AssetsType.ASSETS_EGGS.id.byteValue())).longValue();
//                            //如果不存在账号就初始化
//                            userAssetsRepository.initAllCount(tbUserEggsAccumulateHistory.getUid());
//                            //更新用户鸟蛋账户
//                            int count = eTbUserAssetsMapper.updateEffectiveAccumulate(tbUserEggsAccumulateHistory.getUid(), AssetsType.ASSETS_EGGS.id.byteValue(), accumulate);
//                            //首次充值送蛋壳
//                            APIRequest<ReqUserAccumulateModify> apiRequest = new APIRequest<ReqUserAccumulateModify>();
//                            ReqUserAccumulateModify reqUserAccumulateModify = new ReqUserAccumulateModify();
//                            reqUserAccumulateModify.setSystemCode(Constants.ASSETS_SYSTEM_CODE);
//                            reqUserAccumulateModify.setBusinessCode(Constants.ASSETSS_SHELL_BY_EGGS_RECHANGE_CODE);
//                            reqUserAccumulateModify.setAssetsType(AssetsType.ASSETS_SHELL.id.byteValue());
//                            reqUserAccumulateModify.setUid(tbUserEggsAccumulateHistory.getUid());
//                            reqUserAccumulateModify.setPayReceive(AssetsPayReceive.SYSTEM.getName());
//                            reqUserAccumulateModify.setReceiver(tbUserEggsAccumulateHistory.getReceiver());
//                            apiRequest.setData(reqUserAccumulateModify);
//                            APIResponse apiResponse = userAssetsService.modifyAccumulate(apiRequest);
//                            if (apiResponse.isRet()) {
//                                //发给用户中心消息
//                                UserTaskMsg userTaskMsg = new UserTaskMsg();
//                                userTaskMsg.setUid(tbUserEggsAccumulateHistory.getUid());
//                                userTaskMsg.setTaskId(TaskEnum.TASK_ENUM__ADD_EGGSHELLS.getId());
//                                //给任务中心发送消息
//                                MqRequestMsg mqRequestMsg = new MqRequestMsg();
//                                mqRequestMsg.setTopic(Constants.MQ_TOPIC_TASK_TOPIC);
//                                mqRequestMsg.setTag(Constants.MQ_TOPIC_TASK_TAG);
//                                mqRequestMsg.setMsgId(tbUserEggsAccumulateHistory.getUid().toString());
//                                mqRequestMsg.setBody(ObjectUtil.toByteArray(userTaskMsg));
//                                qcMsgClient.asyncSend(mqRequestMsg);
//                            }
//                            //账号更新成功更新历史记录
//                            if (count == 1) {
//                                int updateAccumulateHistoryCount = eggsAccumulateHistoryRepository.updateAccumulateHistory(Constants.ASSETS_EGGS_RECHANGE_CODE, orderNotifyMsg.getOutTradeNo(), accumulate);
//                                if (updateAccumulateHistoryCount != 1) {
//                                    //回滚
//                                    throw new BizException(AssetsErrorEnum.UPDATE_ACCUMULATE_HISTORY_ERROR);
//                                } else {
//                                    //打印日志
//                                }
//                            } else {
//                                //回滚
//                                throw new BizException(AssetsErrorEnum.UPDATE_EGGES_ACCUMULATE_ERROR);
//                            }
//                        } else {
//                            //回滚
//                            throw new BizException(AssetsErrorEnum.UPDATE_ACCUMULATE_HISTORY_ERROR);
//                        }
//                        break;
//                    //支付失败，进行取消订单处理
//                    case OrderNotifyMsg.RESULT_CODE_USER_PAY_FAIL:
//                        //更新历史状态
//                        eggsAccumulateHistoryRepository.updateRechangeStatus(orderNotifyMsg.getOutTradeNo(), StatusType.DISABLE.id.byteValue());
//                        break;
//                }
//            }
//        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class,isolation = Isolation.READ_COMMITTED)
    public void batchAddEggClub(MessageExt messageExt) {
        byte[] bodyByte = messageExt.getBody();
        //获取成功返回的信息
        Map<Integer,Long> assetsMap = (Map<Integer,Long>) ObjectUtil.toObject(bodyByte);
//        List<ReqBatchAddEgg> reqBatchAddEggList=new ArrayList<ReqBatchAddEgg>();
//        logger.info("俱乐部批量添加鸟蛋"+ GsonUtils.toJson(assetsMap));
//        List<Integer> uidList=new ArrayList<Integer>();
//        ReqBatchAddEgg reqBatchAddEgg=null;
//        for(Integer uid:assetsMap.keySet()){
//            uidList.add(uid);
//            reqBatchAddEgg=new ReqBatchAddEgg();
//            reqBatchAddEgg.setUid(uid);
//            reqBatchAddEgg.setAccumulate(assetsMap.get(uid));
//            reqBatchAddEggList.add(reqBatchAddEgg);
//        }
//        eTbUserAssetsMapper.batchAddEggClub(reqBatchAddEggList);
//        TbUserAssetsExample tbUserAssetsExample=new TbUserAssetsExample();
//        tbUserAssetsExample.createCriteria().andUidIn(uidList).andAssetsTypeEqualTo(AssetsType.ASSETS_EGGS.id.byteValue());
//        //一次性获取用户更新完后数据
//        List<TbUserAssets> tbUserAssetsList=tbUserAssetsMapper.selectByExample(tbUserAssetsExample);
//        List<TbUserEggsAccumulateHistory> tbUserEggsAccumulateHistoryList=new ArrayList<TbUserEggsAccumulateHistory>();
//        TbUserEggsAccumulateHistory tbUserEggsAccumulateHistory=null;
//        for(TbUserAssets tbUserAssets:tbUserAssetsList){
//            String serialNumber = CommonUtils.generateBusinessOrderNo(Constants.ASSETS_SYSTEM, tbUserAssets.getUid());
//            tbUserEggsAccumulateHistory=new TbUserEggsAccumulateHistory();
//            try{
//                APIResponse<RespUserInfoBase> respUserInfoBaseAPIResponse=userServiceFacade.queryUserInfo(tbUserAssets.getUid());
//                logger.info("获取用户信息"+ GsonUtils.toJson(respUserInfoBaseAPIResponse));
//                if(null != respUserInfoBaseAPIResponse.getData()){
//                    tbUserEggsAccumulateHistory.setNickName(respUserInfoBaseAPIResponse.getData().getNickName());
//                    tbUserEggsAccumulateHistory.setMobile(respUserInfoBaseAPIResponse.getData().getMobile());
//                    tbUserEggsAccumulateHistory.setReceiver(respUserInfoBaseAPIResponse.getData().getNickName());
//                }
//            }catch (Exception e){
//
//            }
//            tbUserEggsAccumulateHistory.setUid(tbUserAssets.getUid());
//            tbUserEggsAccumulateHistory.setAccumulate(assetsMap.get(tbUserAssets.getUid()));
//            tbUserEggsAccumulateHistory.setOpBefore(tbUserAssets.getAccumulate()-assetsMap.get(tbUserAssets.getUid()));
//            tbUserEggsAccumulateHistory.setOpAfter(tbUserAssets.getAccumulate());
//            tbUserEggsAccumulateHistory.setOpType(OpType.RECEIVE.id.byteValue());
//            tbUserEggsAccumulateHistory.setBusinessCode("CLUB_EGG_WEEK_TASK_CODE");
//            tbUserEggsAccumulateHistory.setSystemCode(Constants.CLUB_SYSTEM_CODE);
//            tbUserEggsAccumulateHistory.setStatus(StatusType.EFFECTIVE.id.byteValue());
//            tbUserEggsAccumulateHistory.setPayReceive(AssetsPayReceive.SYSTEM.getName());
//            tbUserEggsAccumulateHistory.setInfo("任务奖励");
//            tbUserEggsAccumulateHistory.setSerialNumber(serialNumber);
//            tbUserEggsAccumulateHistoryList.add(tbUserEggsAccumulateHistory);
//        }
//        logger.info("俱乐部批量添加鸟蛋历史明细数据"+ GsonUtils.toJson(tbUserEggsAccumulateHistoryList));
//        //批量更新历史表
//        eTbUserEggsAccumulateHistoryMapper.batchAdd(tbUserEggsAccumulateHistoryList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class,isolation = Isolation.READ_COMMITTED)
    public void batchModifyEgg(MessageExt messageExt) {
        byte[] bodyByte = messageExt.getBody();
        //获取成功返回的信息
        List<ReqUserAccumulateModify> reqUserAccumulateModifyList = (List<ReqUserAccumulateModify>) ObjectUtil.toObject(bodyByte);

    }
}
